var rldMap = null;//风险级别字典
/**
 * 通知管理初始化
 */
var PatienList = {
    id: "patientListTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1
};

/**
 * 初始化表格的列
 */
PatienList.initColumn = function () {
    return [
        {visible: false},
        {title: '姓名', field: 'caseName', align: 'left', width:70, valign: 'middle', sortable: false},
        {title: '病案号', field: 'caseMrno', align: 'left', width:80,valign: 'middle', sortable: false},
        {title: '性别', field: 'caseSex', align: 'center', width:50, valign: 'middle', sortable: false},
        {title: '年龄', field: 'caseAge', align: 'center', width:50, valign: 'middle', sortable: false},
        {title: '入院日期', field: 'admDate', align: 'left', width:180,valign: 'middle', sortable: false},
        {title: '出院日期', field: 'dishDate', align: 'left', width:180,valign: 'middle', sortable: false},
        {title: '入院次数', field: 'admNums', align: 'center', width:80,valign: 'middle', sortable: false},
        {title: '住院天数', field: 'admDays', align: 'center', width:80,valign: 'middle', sortable: false},
        {title: '入组病种', field: 'entityName', align: 'left', width:180,valign: 'middle', sortable: false},
        {title: '住院费用', field: 'costs', align: 'center', width:120,valign: 'middle', sortable: false},
        {title: '离院方式', field: 'dishWay', align: 'left', width:180,valign: 'middle', sortable: false},
        {title: '出院科室', field: 'dishDept', align: 'left', width:120,valign: 'middle', sortable: false},
        {title: '主治医生', field: 'admDoctorName', align: 'left', width:80,valign: 'middle', sortable: false},
        {title: '是否上报', field: 'isReport', align: 'center', width:80,valign: 'middle', sortable: false}
    ];
};

/**
 * 打开查看病种入组病例详情
 */
PatienList.show = function (episodeId, id, name, mrNum, dishDate) {
    if (id) {
        var title = "姓名:" + name + "|" + "病案号:" + mrNum + "|" + "出院日期:" + dishDate;
        var index = Sys.open_c(title, '/sds/sdsqcformshow?mrListId=' + id + '&checkPerm=0&channel=1');
        this.layerIndex = index;
    }
};

/**
 * 导出数据-不同条件
 */
PatienList.exportExcel = function (){

    var startDate = $('#startDate').datebox('getValue');
    var endDate = $('#endDate').datebox('getValue');
    var queryData = {};
    queryData['stateType'] = $('#stateType').datebox('getValue');    //统计类型
    queryData['startDate'] = startDate;    //获取页面开始时间
    queryData['endDate'] = endDate;    //获取页面结束时间
    queryData['office'] = $('#office').datebox('getValue');//部门
    queryData['depart'] = $('#depart').datebox('getValue');//科室
    queryData['entityType'] = $('#entityType').datebox('getValue');//患者类别
    queryData['doctor'] = $('#doctor').val();//主治医生
    queryData['stateType'] = $('#stateType').datebox('getValue');//患者类别

    if(queryData['startDate']!=""){
        queryData['startDate'] = queryData['startDate'] + " 00:00:00";
    }
    if(queryData['endDate']!=""){
        queryData['endDate'] = queryData['endDate'] + " 23:59:59";
    }
    var longStart = Date.parse(startDate);
    var longEnd = Date.parse(endDate);
    if(longStart>longEnd){
        Sys.error("开始日期不可大于结束日期");
        return false;
    }

    Sys.loading("数据文件生成中,请耐心等待");
    var ajax = new $ax(Sys.backendPath + "/sds/case/createExcel", function(data){
        Sys.closeLoading();
        if(data.message=="DHCC"){
            Sys.info("无数据可以导出，请更改查询条件。");
        }else{
            window.location.href = Sys.backendPath + "/sds/case/excelDown/"+data.message;
            // PatienList.table.refresh();
        }
    },function(data){
        Sys.error("数据生成失败!" + data.responseJSON.message + "!");
    });
    ajax.set(queryData);
    ajax.setAsync(true);
    ajax.start();
}

/**
 * 查询病例
 */
PatienList.search = function (){
    var startDate = $('#startDate').datebox('getValue');
    var endDate = $('#endDate').datebox('getValue');
    var queryData = {};
    queryData['stateType'] = $('#stateType').datebox('getValue');    //统计类型
    queryData['startDate'] = startDate;    //获取页面开始时间
    queryData['endDate'] = endDate;    //获取页面结束时间
    queryData['office'] = $('#office').datebox('getValue');//部门
    queryData['depart'] = $('#depart').datebox('getValue');//科室
    queryData['doctor'] = $('#doctor').val();//主治医生
    queryData['entityType'] = $('#entityType').datebox('getValue');//患者类别
    queryData['stateType'] = $('#stateType').datebox('getValue');//患者类别

    if(queryData['startDate']!=""){
        queryData['startDate'] = queryData['startDate'] + " 00:00:00";
    }
    if(queryData['endDate']!=""){
        queryData['endDate'] = queryData['endDate'] + " 23:59:59";
    }

    var longStart = Date.parse(startDate);
    var longEnd = Date.parse(endDate);
    if(longStart>longEnd){
        Sys.error("开始日期不可大于结束日期");
        return false;
    }
    var entityId = $('#entityType').datebox('getValue')
    if (entityId && entityId !== "") {
        var defaultColunms = [
            {visible: false},
            {title: '患者姓名', field: 'caseName', align: 'left', width:80, valign: 'middle', sortable: false},
            {title: '是否上报', field: 'isReport', align: 'center', width:80,valign: 'middle', sortable: false}
        ];
        var fontSize = window.getComputedStyle(document.getElementById(PatienList.id)).fontSize;
        var ajax = new $ax(Sys.backendPath + "/sds/case/getCaseColumn", function(data){
            for (var i = 0; i < data.length; i++) {
                var textWidth = getTextWidth(data[i].btDesc, fontSize) + 25;
                var column = {
                    title: data[i].btDesc,
                    field: data[i].id,
                    align: 'center',
                    width: textWidth,
                    valign: 'middle',
                    sortable: false
                }
                defaultColunms.push(column);
            }
            $('#'+PatienList.id).bootstrapTable('destroy');
            var table = new BSTable(PatienList.id, Sys.backendPath + "/sds/case/list2", defaultColunms);
            table.setPaginationType("server");
            table.setQueryParams(queryData);
            table.setShowColumns(false);
            table.setShowRefresh(false);
            table.setShowToggle(false);
            table.setPageSize(15);
            table.setSubHeight(-27);

            PatienList.table = table.init();
            table.refresh({query: queryData,pageNumber: 1});
        },function(data){
            layer.msg("查询失败!");
        });
        ajax.set({"entityId":$('#entityType').datebox('getValue')});
        ajax.start();
    } else {
        $('#'+PatienList.id).bootstrapTable('destroy');
        var defaultColunms = PatienList.initColumn();
        var table = new BSTable(PatienList.id, Sys.backendPath + "/sds/case/list", defaultColunms);
        table.setPaginationType("server");
        table.setQueryParams(queryData);
        table.setShowColumns(false);
        table.setShowRefresh(false);
        table.setShowToggle(false);
        table.setPageSize(15);
        table.setSubHeight(-27);

        PatienList.table = table.init();
        table.refresh({query: queryData,pageNumber: 1});
    }
}

function getTextWidth(text, fontSize) {
    const _span = document.createElement('span');
    _span.innerText = text;
    _span.style.fontSize = fontSize + 'px';
    _span.style.position = 'absolute';
    _span.style.visibility = 'hidden'; // 隐藏元素以避免干扰页面布局
    document.body.appendChild(_span);
    const width = _span.offsetWidth;
    document.body.removeChild(_span); // 清理添加的元素
    return width;
}

/**
 * //根据父级机构 查询子机构
 */
PatienList.officeChange = function(that){
    var ajax = new $ax(Sys.backendPath + "/sds/common/deptListByHospId", function(data){
        $('#depart').combobox({
            data:data,
            valueField:'value',
            textField:'text',
            defaultFilter: 6,
            onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
                $(this).combobox("setValue", "");
            }
        });
    },function(data){
        layer.msg("查询失败!" + data.responseJSON.message + "!",{icon: 2});
    });
    ajax.set({"hospID":that.value,"id":"depart"});
    ajax.start();
}


$(function () {
    //科室
    $('#depart').combobox({
        data:$.parseJSON($("#departMap").val()),
        valueField:'value',
        textField:'text'
    });
    //院区
    $('#office').combobox({
        data:$.parseJSON($("#officeMap").val()),
        valueField:'value',
        textField:'text',
        defaultFilter: 6,
        onSelect:PatienList.officeChange,
        onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
            var hospId = $('#hospitalId').val();
            if (hospId != "") {
                $(this).combobox("setValue", hospId);
                $(this).combobox('disable');
            } else {
                var val = $(this).combobox("getData");
                if (val.length == 2) {//如果就一个院区 加上全部=2
                    $(this).combobox("setValue", val[1].value);
                    PatienList.officeChange(val[1]);
                } else {
                    $(this).combobox("setValue", "");
                }
            }
        }
    });
    //病种
    $('#entityType').combobox({
        data:$.parseJSON($("#entityMap").val()),
        valueField:'value',
        textField:'text',
        defaultFilter: 6
    });
    // 状态
    $('#stateType').combobox({
        data:[
            {value:"",text:"全部"},
            {value:"I",text:"已确认"},
            {value:"Save",text:"保存"},
            {value:"Submit",text:"提交"},
            {value:"Check",text:"已审核"},
            {value:"Back",text:"退回"},
            {value:"Up",text:"已上报"}
        ],
        valueField:'value',
        textField:'text',
        defaultFilter: 6
    });
    //渲染datebox --没有渲染的话 图标左右间距不等
    $('.hisui-datebox').datebox({});

    //默认一星期
    $('#startDate').datebox('setValue', timeStamp2String(new Date().getTime()-(1000 * 60 * 60 * 24*180)));
    $('#endDate').datebox('setValue', timeStamp2String(new Date().getTime()));

    var startDate = $('#startDate').datebox('getValue');//开始日期
    var endDate = $('#endDate').datebox('getValue');//结束日期
    startDate = startDate + " 00:00:00";
    endDate = endDate + " 23:59:59";
    var stateType = $('#stateType').combobox('getValue');
    var entityType = $('#entityType').combobox('getValue');
    var doctor = $('#doctor').val();
    var defaultColunms = PatienList.initColumn();
    var table = new BSTable(PatienList.id, Sys.backendPath + "/sds/case/list", defaultColunms);
    table.setPaginationType("server");
    table.setQueryParams({stateType:stateType,entityType:entityType,startDate:startDate,endDate:endDate,office:'',depart:'',doctor:doctor});
    table.setShowColumns(false);
    table.setShowRefresh(false);
    table.setShowToggle(false);
    table.setPageSize(15);
    table.setSubHeight(-27);
    // table.setResizable(true);

    PatienList.table = table.init();
    table.refresh();
});


//在Jquery里格式化Date日期时间数据
function timeStamp2String(time){
    var datetime = new Date();
    datetime.setTime(time);
    var year = datetime.getFullYear();
    var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
    var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
    return year + "-" + month + "-" + date;
}